import React, { useState, useEffect } from "react";
import { Menu } from "antd";
import type { MenuProps } from "antd";

import type { FieldIdentifiers, MenuItemType as CustomMenuItemType, MenuItem } from "../../global.ts";
import { findNodeByKey } from "../../utils/fun.ts";

export interface MenuClickCallbackProps {
  key: string;
  label: string;
  path: string;
} 

export interface LeftNavMenuProps {
  initialLoadMenu?: boolean;
  menuApiUrl?: string;
  theme?: "light" | "dark";
  menuClickCallback?: (clickResult: MenuClickCallbackProps) => void;
  menuType?: MenuProps['mode'];
  items: Required<MenuProps>['items'];
  initialSelectedKey?: string;
  initialExpandedKeys?: string[];
}

const LeftNavMenu: React.FC<LeftNavMenuProps> = ({
  initialLoadMenu,
  menuApiUrl,
  theme = 'light',
  menuClickCallback,
  menuType = 'inline',
  items,
  initialSelectedKey,
  initialExpandedKeys = [],
}: LeftNavMenuProps) => {
  const [selectedKeys, setSelectedKeys] = useState<string[]>(
    initialSelectedKey ? [initialSelectedKey] : []
  );
  const [openKeys, setOpenKeys] = useState<string[]>(initialExpandedKeys);

  useEffect(() => {
    if (initialLoadMenu && menuApiUrl) {
      const loadMenu = async () => {
        try {
          // 实现API加载逻辑
        } catch (error) {
          console.error('Failed to load menu:', error);
        }
      };
      loadMenu();
    }
  }, [initialLoadMenu, menuApiUrl]);

  const handleMenuClick: MenuProps['onClick'] = (info: any) => {
    const clickedItem = findNodeByKey(info.key, items || []);
    if (clickedItem) {
      setSelectedKeys([info.key]);
      menuClickCallback?.({
        key: clickedItem.key,
        label: clickedItem.label,
        path: clickedItem.path,
      });
    }
  };

  const handleOpenChange: MenuProps['onOpenChange'] = (keys) => {
    setOpenKeys(keys);
  };

  return (
    <Menu
      mode={menuType}
      theme={theme}
      items={items}
      selectedKeys={selectedKeys}
      openKeys={openKeys}
      onClick={handleMenuClick}
      onOpenChange={handleOpenChange}
      style={{ width: '100%', height: '100%' }}
    />
  );
};

export default LeftNavMenu;
